<template>
  <div style="height: 100%;background-color:white ;">
    <DataPermissionDialog ref="dataPermissionDialog" :userName="crtUser.userName"/>
    <el-row>
      <el-col :span="12">
        <div style="display: inline-block">
          <div style="display: inline-block"><span></span></div>
        </div>
        <el-button v-if="this.system==='outside'" size="small" type="success" @click="editUser(null)">新建用户
        </el-button>
      </el-col>
      <el-col :span="12" style="right: auto">
        <div>
          <div style="width: 430px; float: right">
            <el-input v-model="userName" placeholder="请输入用户名" size="small" @keyup.enter.native="getTableData">
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
              <el-button slot="append" :icon="appendIcon" v-on:click="switchAppend"></el-button>
            </el-input>
          </div>
          <div v-if="showAdvance" id="advance" style="padding: 10px; float: right">
            <div>
              <div>
                <div style="width: 100px;text-align:right; display: inline-block">
                  <span>姓名</span>
                </div>
                <div style="display: inline-block">
                  <el-input v-model="name" placeholder="请输入名称" size="small"
                            style="width: 300px;margin-top: 10px"></el-input>
                </div>
              </div>
            </div>
            <div style="margin-top: 60px; right: 10px;">
              <el-row>
                <el-col :offset="7" :span="9">
                  <div style="margin-left: 90px;height: 32px; width: 88px;">
                    <el-button size="small" v-on:click="advanceCancel">取 消</el-button>
                  </div>
                </el-col>
                <el-col :offset="0.8" :span="2">
                  <div style="margin-left: 5px;height: 32px; width: 88px;">
                    <el-button size="small" type="success" v-on:click="replacement">重 置</el-button>
                  </div>
                </el-col>
                <el-col :offset="2" :span="2">
                  <div style="margin-left: 5px;height: 32px; width: 88px;">
                    <el-button size="small" type="success" v-on:click="advanceConfirm">确 定</el-button>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <div>
        <el-table :data="tableData" :height="tableHeight" border stripe style="width: 100%;margin-top: 10px">
          <el-table-column label="用户名" min-width="300" prop="userName"></el-table-column>
          <el-table-column label="姓名" min-width="100" prop="name"></el-table-column>
          <el-table-column label="角色" min-width="150" prop="roleNames"></el-table-column>
          <el-table-column label="手机号" min-width="150" prop="phoneNumber"></el-table-column>
          <el-table-column label="邮箱号" min-width="150" prop="emailAddress"></el-table-column>
          <el-table-column label="状态" min-width="150" prop="">
            <template slot-scope="scope">
              <el-switch
                active-text="启用"
                :value="scope.row.status"
                inactive-color="#666666"
                inactive-text="停用"
                :active-value="1"
                :inactive-value="0"
                @change="updateUser(scope.row)"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="200">
            <template slot-scope="scope">
              <span><el-link type="success"
                             @click.prevent="editUser(scope.row)">编辑</el-link></span>
              <span><el-link type="success"
                             @click.prevent="editBookPermission(scope.row)">数据权限</el-link></span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-row>
    <el-row>
      <div style="margin-top: 10px">
        <el-pagination
          v-if="multiplePages"
          :page-size="pageSize"
          :page-sizes="[5, 10, 15, 20, 50, 100]"
          :total="totalNum"
          background
          layout="total, sizes, prev, pager, next, jumper"
          style="text-align: right;"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"></el-pagination>
      </div>
    </el-row>
    <el-dialog :title="userType" :visible.sync="newUserDialogVisible" width="500px" @click="closeNewDialog">
      <el-row>
        <el-col :span="6">
          <span class="label">用户名<em style="color: red">*</em></span>
        </el-col>
        <el-col :span="18">
          <el-input v-if="user.kind===1" v-model="user.userName" disabled="true" placeholder="请输入用户名"/>
          <el-input v-else v-model="user.userName" placeholder="请输入用户名"/>
        </el-col>
      </el-row>
      <el-row style="margin-top: 10px">
        <el-col :span="6">
          <span class="label">姓名 <em style="color: red">*</em></span>
        </el-col>
        <el-col :span="18">
          <el-input v-if="user.kind===1" v-model="user.name" disabled="true" placeholder="请输入姓名"></el-input>
          <el-input v-else v-model="user.name" placeholder="请输入姓名"></el-input>
        </el-col>
      </el-row>
      <el-row style="margin-top: 10px">
        <el-col :span="6">
          <span class="label">手机号</span>
        </el-col>
        <el-col :span="18">
          <el-input v-model="user.phoneNumber" placeholder="请输入手机号"></el-input>
        </el-col>
      </el-row>
      <el-row style="margin-top: 10px">
        <el-col :span="6">
          <span class="label">邮箱</span>
        </el-col>
        <el-col :span="18">
          <el-input v-model="user.emailAddress" placeholder="邮箱"></el-input>
        </el-col>
      </el-row>
      <el-row v-if="userType=='新建'" style="margin-top: 10px">
        <el-col :span="6">
          <span class="label">密码</span>
        </el-col>
        <el-col :span="18">
          <el-input v-model="user.password" placeholder="密码"></el-input>
        </el-col>
      </el-row>
      <el-row v-if="userType==='编辑'&&user.kind===0" style="margin-top: 10px">
        <el-col :span="6">
          <span class="label">密码</span>
        </el-col>
        <el-col :span="18">
          <div style="margin-top: 10px">
            <el-switch
              :value="user.password"
              active-text="重置密码"
              @change="updatePassword(user.password)"/>
          </div>
        </el-col>
      </el-row>
      <el-row style="margin-top: 10px">
        <el-col :span="6">
          <span class="label">角色<em style="color: red">*</em></span>
        </el-col>
        <el-col :span="18">
          <el-select v-model="roleId" multiple placeholder="请选择" style="width: 345px">
            <el-option
              v-for="item in roles"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeNewDialog">取 消</el-button>
        <el-button type="primary" @click="newUser">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import DataPermissionDialog from "./DataPermissionDialog";

export default {
  name: "UserTable",
  components: {DataPermissionDialog},
  props: {
    system: String,
  },
  data() {
    return {
      crtUser: {},
      tableData: [],
      multiplePages: true,
      appendIcon: "el-icon-caret-bottom",
      noData: true,
      totalNum: 0,
      showAdvance: false,
      currentPage: 0, // 第几页
      pageSize: 10, // 每页显示的数据个数
      newUserDialogVisible: false,
      userType: '新建',
      user: {},
      roleName: '',
      tableHeight: '',
      userName: '',
      name: '',
      roles: [],
      roleId: [],
      password: false
    }
  },
  methods: {
    editBookPermission(crtUser) {
      this.crtUser = crtUser
      this.$refs.dataPermissionDialog.visible = true
    },
    editUser(row) {
      if (row) {
        this.userType = '编辑'
        this.user = JSON.parse(JSON.stringify(row))
        this.roleId = row.roleIds
        this.password = false
      } else {
        this.user = {};
        this.roleId = []
        this.userType = '新建';

      }
      this.newUserDialogVisible = true
    },
    newUser() {
      let massage = "";
      if (UTIL.isEmpty(this.user.name)) {
        this.$message.warning("请填写姓名")
        return;
      }
      if (UTIL.isEmpty(this.user.userName)) {
        this.$message.warning("请填写用户名")
        return;
      }

      if (this.userType === '新建') {
        if (UTIL.isNotEmpty(this.user.password)) {
          if (this.user.password.length < 8 || this.user.password.length > 14) {
            this.$message.warning("密码长度为8-14位")
            return
          }
          if (/[\u4e00-\u9fa5]/.test(this.user.password) || /[\s]/.test(this.user.password)) {
            this.$message.warning("密码不包含空格和汉字")
            return
          }
          if (!/^(((?=.*[0-9])(?=.*[a-zA-Z])|(?=.*[0-9])(?=.*[^\s0-9a-zA-Z])|(?=.*[a-zA-Z])(?=.*[^\s0-9a-zA-Z]))[^\s]+)$/.test(this.user.password)) {
            this.$message.warning("密码必须包含字母，数字以及标点符号至少包含两种")
            return
          }
        }
      }
      if (this.roleId.length <= 0) {
        this.$message.warning("请选择角色")
        return;
      }
      if (this.userType === '新建') {
        if (UTIL.isEmpty(this.user.password)) {
          massage = "您将用默认密码"
        } else {
          massage = "您的密码为" + this.user.password
        }
        this.$confirm(massage, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.add()
        })
      } else {
        this.add()
      }
    },
    add() {
      if (this.userType === '新建') {
        this.user.kind = 1
      }
      let param = JSON.parse(JSON.stringify(this.user))
      param.roleIds = this.roleId
      this.axios.post(CONST.SERVICE_REST_PACKAGE + "UserCtrl/newUser", param)
        .then(() => {
          this.closeNewDialog()
          this.getTableData()
          this.newUserDialogVisible = false
        })
    },
    getTableData() {
      this.axios.get(CONST.SERVICE_REST_PACKAGE + "UserCtrl/selectUserList", {
        params: {
          name: this.name,
          userName: this.userName,
          system: this.system,
          currentPage: this.currentPage,
          pageSize: this.pageSize,
        }
      }).then((response) => {
        this.totalNum = response.data.total;
        this.tableData = response.data.records;
        console.log(response)
      })
    },
    closeNewDialog() {
      this.user = {};
      this.roleId = []
      this.newUserDialogVisible = false
    },
    advanceCancel() {
      this.showAdvance = false;
    },
    replacement: function () {
      this.userName = '';
      this.name = ''
    },
    advanceConfirm() {
      this.getTableData();
      this.showAdvance = false;
    },
    switchAppend: function () {
      if (this.showAdvance) {
        this.showAdvance = false;
        this.appendIcon = "el-icon-caret-bottom";
      } else {
        this.showAdvance = true;
        this.appendIcon = "el-icon-caret-top";
      }
    },
    handleCurrentChange: function (val) {
      this.currentPage = val;
      this.getTableData();
    },
    handleSizeChange(value) {
      this.pageSize = value
      this.getTableData()
    },
    updateUser(user) {
      let message = "";
      if (user.status === 1) {
        message = "您确定要停用该用户，用户停用后，将无法正常登陆和使用知识管理平台，和用户相关的数据保留。"
      } else {
        message = "您确定要重新启用该用户，启用后，该用户将可以正常登陆和使用知识管理平台。"
      }
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let param = new URLSearchParams();
        param.append("user", JSON.stringify(user))

        this.axios.post(CONST.SERVICE_REST_PACKAGE + "UserCtrl/updateUser", param)
          .then(() => {
            this.getTableData()
          })
      })
    },
    updatePassword() {
      this.$confirm("你是否重置到默认密码", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.user.password = true
      })
    }
  },
  activated() {
    this.getTableData()
  },
  created() {
    this.tableHeight = CONST.WORKSPACE_HEIGHT - 210;
    this.getTableData()
    this.axios.get(CONST.SERVICE_REST_PACKAGE + "UserCtrl/selectRoleName", {
      params: {}
    }).then((response) => {
      this.roles = response.data
    })
  }
}

</script>

<style scoped>

</style>
